package com.seu.magicfilter

import com.seu.magicfilter.camera.CameraEngine
import com.seu.magicfilter.filter.helper.MagicFilterType
import com.seu.magicfilter.helper.SavePictureTask
import com.seu.magicfilter.helper.SavePictureTask.OnPictureSaveListener
import com.seu.magicfilter.utils.MagicParams
import com.seu.magicfilter.widget.MagicCameraView
import com.seu.magicfilter.widget.base.MagicBaseView
import java.io.File

class MagicEngine private constructor(builder: Builder) {
    var magicBaseView: MagicBaseView?
    fun setFilter(type: MagicFilterType?) {
        magicBaseView?.setFilter(type)
    }

    /**
     * 保存图片
     */
    fun savePicture(file: File?, listener: OnPictureSaveListener?) {
        val savePictureTask = SavePictureTask(file, listener)
        magicBaseView?.savePicture(savePictureTask)
    }

    /**
     * 开始录像
     */
    fun startRecord(outputMediaFile: File) {
        if (magicBaseView is MagicCameraView) (magicBaseView as MagicCameraView).setOutFile(outputMediaFile).changeRecordingState(true)
    }

    /**
     * 停止录像
     */
    fun stopRecord() {
        if (magicBaseView is MagicCameraView) (magicBaseView as MagicCameraView).changeRecordingState(false)
    }
    fun setBeautyLevel(level: Int) {
        if (magicBaseView is MagicCameraView && MagicParams.beautyLevel != level) {
            MagicParams.beautyLevel = level
            (magicBaseView as MagicCameraView).onBeautyLevelChanged()
        }
    }

    /**
     * 切换模式
     */
    fun switchCamera() {
        CameraEngine.switchCamera()
    }

    class Builder {
        var buildMagicBaseView: MagicBaseView? = null
        fun build(magicBaseView: MagicBaseView): MagicEngine {
            MagicParams.context = magicBaseView.context
            buildMagicBaseView = magicBaseView
            magicEngine = MagicEngine(this)
            return magicEngine as MagicEngine
        }
    }

    companion object {
        private var magicEngine: MagicEngine? = null
        fun getInstance():MagicEngine? {
            return magicEngine ?: throw NullPointerException("MagicEngine must be built first")
        }

    }

    init {
        magicBaseView = builder.buildMagicBaseView
    }
}